package com.wu.webstep4.customUrl;

import java.util.Collection;
import java.util.Iterator;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

@Component
//用于设置判断当前用户是否可以访问被保护资源的逻辑
public class MyAccessDecisionManager implements AccessDecisionManager {

	@Override
	/*
	 * @param 请求该保护资源的用户对象
	 * @param 被调用的保护资源
	 * @param 有权限调用该资源的角色集合
	 */
	public void decide(Authentication authentication, Object object,
			Collection<ConfigAttribute> configAttributes)
			throws AccessDeniedException, InsufficientAuthenticationException {
		Iterator<ConfigAttribute> ite = configAttributes.iterator();
		//遍历configAttributes，查看当前用户是否有对应的权限访问该保护资源
		while (ite.hasNext()) {
			ConfigAttribute ca = ite.next();
			String needRole = ca.getAttribute();
			for (GrantedAuthority ga : authentication.getAuthorities()) {
				if (ga.getAuthority().equals(needRole)) {
					// 匹配到有对应角色,则允许通过
					return;
				}
			}
		}
		// 该url有配置权限,但是当前登录用户没有匹配到对应权限,则禁止访问
		throw new AccessDeniedException("not allow");
	}

	@Override
	public boolean supports(ConfigAttribute attribute) {
		return true;
	}

	@Override
	public boolean supports(Class<?> clazz) {
		return true;
	}

}


